<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}文章</h1>
    <el-form label-width="80px" @submit.native.prevent="save">
      <el-form-item label="所属分类">
        <el-select v-model="model.categories" placeholder="请选择" multiple>
          <el-option
            v-for="item in categories"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="文章标题">
        <el-input v-model="model.title"></el-input>
      </el-form-item>
      <el-form-item label="文章内容">
        <vue-editor
          v-model="model.body"
          useCustomImageHandler
          @image-added="handleImageAdded"
        >
        </vue-editor>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { VueEditor } from 'vue2-editor'
export default {
  components: {
    VueEditor
  },
  props: {
    id: {}
  },
  data () {
    return {
      model: {
        body: '<h1>Some initial content</h1>'
      },
      categories: []
    }
  },
  methods: {
    // 保存文章
    async save () {
      if (!this.model.title) return this.$message({ type: 'error', message: '请填写数据' })

      if (this.id) {
        // 如果传入了id就发送编辑文章名称的请求
        await this.$http.put(`rest/articles/${this.id}`, this.model)
      } else {
        // 没有id就是发送创建文章名称
        await this.$http.post('rest/articles', this.model)
      }
      this.$router.push('/articles/list')
      this.$message({
        type: 'success',
        message: '保存成功'
      })
    },
    // 编辑文章
    async fetch () {
      const res = await this.$http.get(`rest/articles/${this.id}`)
      this.model = res.data
    },
    // 文章分类
    async fetchCategories () {
      const res = await this.$http('rest/categories')
      this.categories = res.data
    },
    async handleImageAdded (file, Editor, cursorLocation, resetUploader) {
      const formData = new FormData()
      formData.append('file', file)
      const { data } = await this.$http.post('/upload', formData)
      Editor.insertEmbed(cursorLocation, 'image', data.url)
      resetUploader()
    }
  },
  created () {
    this.fetchCategories()
    this.id && this.fetch()
  }
}
</script>
